FC_BASE := $(CURDIR)/../..

#specify toolchain
ifeq ($(shell uname),Darwin)
	TOOLCHAIN_PATH:=/Users/yangsheng/Embedded/build-tools/gcc-arm-none-eabi-4_9-2015q1/bin
else
	TOOLCHAIN_PATH:=/home/yangsheng/Embedded/build-tools/gcc-arm-none-eabi-4_9-2015q2/bin
endif

ifeq ($(MAKECMDGOALS),)
	TARGET:= ysfc
	TARGET_BOARD := ysfc
	TARGET_PATH := $(FC_BASE)/platform/arch/arm/cortex_M/stm32f4/ysfc
else
ifneq ($(MAKECMDGOALS),clean)
	TARGET:= $(MAKECMDGOALS)
	TARGET_BOARD := $(MAKECMDGOALS)
	TARGET_PATH := $(FC_BASE)/platform/arch/arm/cortex_M/stm32f4/$(MAKECMDGOALS)
endif
endif

-include $(TARGET_PATH)/Make.defs

OBJ_DIR := $(FC_BASE)/objects

INCLUDE += -I$(FC_BASE)/src
INCLUDE += -I$(FC_BASE)/platform/api

USERSRC += $(shell find $(FC_BASE)/src -name '*.c')

# vpath is used so object files are written to the current directory instead
# of the same directory as their source files
vpath %.c $(dir $(USERSRC)) 

USERSRC := $(filter-out main.c,$(notdir $(USERSRC)))
USERSRC += $(notdir $(wildcard *.c))

CSRC := $(LIBSRC) $(BOARDSRC) $(DRIVERSRC) $(USERSRC)

WARNFLAGS = -Wall -Wextra
OPTLVL:=2 # Optimization level, can be [0, 1, 2, 3, s].
OPTFLAGS = -O$(OPTLVL) -g \
		   -ggdb3 \
		   -ffunction-sections \
		   -fdata-sections

CFLAGS=$(ARCHFLAGS) \
	   $(INCLUDE) \
	   $(OPTFLAGS) \
	   $(CDEFS) \
	   $(WARNFLAGS) \
	   -Wstrict-prototypes \
	   -flto \
	   -std=gnu99 \
	   -fno-builtin \
	   -fverbose-asm

ASFLAGS = $(ARCHFLAGS) \
	  $(CDEFS) \
	  $(INCLUDE) \
	  -g -ggdb3 \
	  -DUSES_CXX \
	  -x assembler-with-cpp

# -Wl,--gc-sections remove unused code
LDFLAGS=$(ARCHFLAGS) -g -Wl,--gc-sections,-T$(LINKER_SCRIPT) --specs=nosys.specs
# LDFLAGS=$(ARCHFLAGS) -g -Wl,--gc-sections,-T$(LINKER_SCRIPT) 

LDLIBS += -lm

#####

OBJ := $(CSRC:%.c=%.o) $(ASRC:%.s=%.o)
OBJ := $(notdir $(OBJ))
OBJ := $(addprefix $(OBJ_DIR)/,$(OBJ))

ysfc : all
	@echo done

oofc : all
	@echo done

discovery : all
	@echo done

all: $(OBJ) 
	@echo LD -o $(TARGET).elf $(notdir $(OBJ)) $(LDFLAGS) $(notdir $(LDLIBS))
	@$(LD) -o $(TARGET).elf $(OBJ) $(LDFLAGS) $(LDLIBS)
	$(OBJCOPY) -O binary $(TARGET).elf $(TARGET).bin

lib: $(OBJ)
	@rm $(OBJ_DIR)/main.o

$(OBJ_DIR)/%.o: %.c
	@echo CC $(notdir $<) $(notdir $@)
	@$(CC) -c $(CFLAGS) -o $@ $<

$(OBJ_DIR)/%.o: %.s
	@echo AS $(notdir $<) $(notdir $@)
	@$(AS) -c $(ASFLAGS) -o $@ $<

.PHONY: clean

clean:
	-rm -f $(OBJ_DIR)/*
	-rm -f *.elf
	-rm -f *.hex
	-rm -f *.bin
